#define Trig 2
#define Echo 3
#define Buzzer 11

float distance;
float temp;

void buzzerdone();

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(Trig,OUTPUT);
  pinMode(Echo,INPUT);
  pinMode(Buzzer,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  //给Trig引脚发送一个10微秒的触发脉冲
  digitalWrite(Trig,LOW);
  delayMicroseconds(2);
  digitalWrite(Trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig,LOW);
  delayMicroseconds(2);

  //pulseIn()返回脉冲的长度,即Echo的回响时间
  temp = float(pulseIn(Echo,HIGH));

  distance = temp*0.017;//结果的单位为厘米

  if(distance < 10)
    buzzerdone();

  //串口输出
  Serial.print("Echo = ");
  Serial.print(temp);
  Serial.print(" || Distance = ");
  Serial.print(distance);
  Serial.print("cm");
  Serial.print("\n");
  delay(1000);

}

void buzzerdone(){
  unsigned char k;
  unsigned char i;
  for(i=10;i>0;i--)
  {
      for(k=0;k<80;k++)
      {
        digitalWrite(Buzzer,HIGH);
        delay(3);
        digitalWrite(Buzzer,LOW);
        delay(3);
        }
      for(k=0;k<100;k++)
      {
        digitalWrite(Buzzer,HIGH);
        delay(2);
        digitalWrite(Buzzer,LOW);
        delay(2);
        }
    }
  }
